package edu.ccit.shudong.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import edu.ccit.shudong.dto.PostDTO;
import edu.ccit.shudong.dto.PostProfileDTO;
import edu.ccit.shudong.dto.UserProfileDTO;
import edu.ccit.shudong.entity.Post;
import edu.ccit.shudong.entity.User;
import edu.ccit.shudong.service.IPostService;
import edu.ccit.shudong.service.IUserService;
import edu.ccit.shudong.utils.JwtUtils;
import edu.ccit.shudong.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Suting Luo
 * @since 2024-06-14
 */
@RestController
@RequestMapping("/posts")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT})
@Api(tags = "帖子")
public class PostController {
    @Autowired
    private IPostService postService;

    @Autowired
    private IUserService userService;

    @ApiOperation("帖子读取")
    @GetMapping("/{id}")
    public Object getOne(
            @ApiParam(value = "帖子ID", name = "id", required = true)@PathVariable("id") Long id) {
        Post post = postService.getById(id);
        User user = userService.getById(post.getUserId());
        UserProfileDTO userProfile = new UserProfileDTO();
        userProfile.fromUser(user);
        post.setUser(userProfile);
        return post != null ? R.ok("成功", post) : R.error("失败");
    }

    @ApiOperation("帖子列表")
    @GetMapping
    public Object getList(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        PostProfileDTO post = postService.getProfileByToken(token);
        List<Post> page = postService.list();
        if (page != null) {
            page.forEach(x -> {
                User user = userService.getById(x.getUserId());
                UserProfileDTO userProfile = new UserProfileDTO();
                userProfile.fromUser(user);
                x.setUser(userProfile);
            });
            return R.ok("帖子列表读取成功", page);
        }
        else {
            return R.ok("帖子列表读取失败");
        }
    }

    @ApiOperation("帖子分页")
    @GetMapping("/{current}/{size}")
    public Object getPage(
            @ApiParam(value = "页码", name = "current", required = true) @PathVariable("current") Long current,
            @ApiParam(value = "页大小", name = "size", required = true) @PathVariable("size") Long size) {
        IPage<Post> page = postService.getPage(current, size);
        return page != null ? R.ok("成功", page) : R.error("失败");
    }

    @ApiOperation("帖子添加")
    @PostMapping()
    public Object addOne(
            HttpServletRequest request,
            @ApiParam(value = "标题", name = "title", required = true) @RequestParam("title") String title,
            @ApiParam(value = "内容", name = "content", required = true) @RequestParam("content") String content
    ) {
        // 从Header获取token
        String token = request.getHeader("Authorization");
//        if (blacklistService.isTokenInBlacklist(token)) return R.error("登录凭证已失效，请重新登录");
//        if (title.trim().isEmpty()) return R.error("标题不能为空");
        if (content.trim().isEmpty()) return R.error("内容不能为空");

        // 从token恢复出userId
        long userId = JwtUtils.getUserId(token);
        Post post = new Post();
        post.setTitle(title);
        post.setContent(content);
        post.setUserId(userId);
        boolean flag = postService.save(post);
        if (flag) {
            User user = userService.getById(userId);
            UserProfileDTO userProfile = new UserProfileDTO();
            userProfile.fromUser(user);
            post.setUser(userProfile);
            return R.ok("帖子添加成功", post);
        }
        return R.error("帖子添加失败");
    }
}
